package org.jeecgframework.web.controller;

import com.mybatis.ext.WiseCoreService;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 服务单派单信息表
 * @date 2018-01-02 13:24:32
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsServiceAssignListController")
public class CbsServiceAssignListController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsServiceAssignListController.class);

    @Autowired
    private CbsServiceAssignListServiceI cbsServiceAssignListService;
    @Autowired
    private SystemService systemService;
    private String message;
    @Autowired
    private ZyFileLogServiceI zyFileLogServiceI;
    @Autowired
    private CbsServiceServiceI cbsServiceServiceI;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    private CbsServiceTaskMapServiceI cbsServiceTaskMapServiceI;
    @Autowired
    private WiseCoreService wiseCoreService;
    @Autowired
    private WxCommonService wxCommonService;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 服务单派单信息表列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsServiceAssign")
    public ModelAndView cbsServiceAssign(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsserviceassignlist/cbsServiceAssignList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsServiceAssignListEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsServiceAssignList, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsServiceAssignListService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 服务单派单信息表新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsServiceAssignList.getId())) {
            cbsServiceAssignList = cbsServiceAssignListService.getEntity(CbsServiceAssignListEntity.class, cbsServiceAssignList.getId());
            req.setAttribute("cbsServiceAssignPage", cbsServiceAssignList);
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/cbsServiceAssign-add");
    }


    /**
     * 添加服务单派单信息表
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单派单信息表添加成功";
        try {
            cbsServiceAssignListService.save(cbsServiceAssignList);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单派单信息表添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 服务单派单信息表编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsServiceAssignList.getId())) {
            cbsServiceAssignList = cbsServiceAssignListService.getEntity(CbsServiceAssignListEntity.class, cbsServiceAssignList.getId());
            req.setAttribute("cbsServiceAssignPage", cbsServiceAssignList);
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/cbsServiceAssign-update");
    }

    /**
     * 更新服务单派单信息表
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单派单信息表更新成功";
        CbsServiceAssignListEntity t = cbsServiceAssignListService.get(CbsServiceAssignListEntity.class, cbsServiceAssignList.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(cbsServiceAssignList, t);
            cbsServiceAssignListService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单派单信息表更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除服务单派单信息表
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsServiceAssignList = systemService.getEntity(CbsServiceAssignListEntity.class, cbsServiceAssignList.getId());
        message = "服务单派单信息表删除成功";
        try {
            cbsServiceAssignListService.delete(cbsServiceAssignList);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单派单信息表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除服务单派单信息表
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单派单信息表删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsServiceAssignListEntity cbsServiceAssign = systemService.getEntity(CbsServiceAssignListEntity.class, id);
                cbsServiceAssignListService.delete(cbsServiceAssign);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单派单信息表删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsserviceassignlist/cbsServiceAssignUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
//    @RequestMapping(params = "exportXls")
//    public String exportXls(CbsServiceAssignListEntity cbsServiceAssignList, HttpServletRequest request, HttpServletResponse response
//            , DataGrid dataGrid, ModelMap modelMap) {
//        CriteriaQuery cq = new CriteriaQuery(CbsServiceAssignListEntity.class, dataGrid);
//        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsServiceAssignList, request.getParameterMap());
//        List<CbsServiceAssignListEntity> cbsServiceAssigns = this.cbsServiceAssignListService.getListByCriteriaQuery(cq, false);
//        modelMap.put(NormalExcelConstants.FILE_NAME, "服务单派单信息表");
//        modelMap.put(NormalExcelConstants.CLASS, CbsServiceAssignListEntity.class);
//        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("服务单派单信息表列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
//                "导出信息"));
//        modelMap.put(NormalExcelConstants.DATA_LIST, cbsServiceAssigns);
//        return NormalExcelConstants.JEECG_EXCEL_VIEW;
//    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
//    @RequestMapping(params = "exportXlsByT")
//    public String exportXlsByT(CbsServiceAssignListEntity cbsServiceAssign, HttpServletRequest request, HttpServletResponse response
//            , DataGrid dataGrid, ModelMap modelMap) {
//        modelMap.put(TemplateExcelConstants.FILE_NAME, "服务单派单信息表");
//        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
//        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
//        modelMap.put(TemplateExcelConstants.CLASS, CbsServiceAssignListEntity.class);
//        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
//        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
//    }
    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsServiceAssignListEntity> listCbsServiceAssignEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsServiceAssignListEntity.class, params);
                for (CbsServiceAssignListEntity cbsServiceAssign : listCbsServiceAssignEntitys) {
                    cbsServiceAssignListService.save(cbsServiceAssign);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    /**
     * 服务商任务页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "facilitatorlist")
    public ModelAndView FacilitatorList(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsserviceassignlist/facilitatorList");
    }

    /**
     * 服务商待办任务页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "facilitatorlistTodo")
    public ModelAndView facilitatorlistTodo(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsserviceassignlist/facilitatorlistTodo");
    }

    /**
     * 区域工程任务页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "argengineerlist")
    public ModelAndView ArgEngineerlist(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsserviceassignlist/argEngineerlist");
    }

    /**
     * 区域工程任务代待办页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "argEngineerlistTodo")
    public ModelAndView ArgEngineerlistTodo(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsserviceassignlist/argEngineerlistTodo");
    }

    /**
     * 工程任务页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "engineerlists")
    public ModelAndView Engineerlist(HttpServletRequest req) {
        String code = req.getParameter("code");
        if (StringUtil.isNotEmpty(code)) {
            req.setAttribute("code", code);
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/engineerlist");
    }

    /**
     * 工程任务页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "engineerlistsTodo")
    public ModelAndView engineerlistsTodo(HttpServletRequest req) {
        String code = req.getParameter("code");
        if (StringUtil.isNotEmpty(code)) {
            req.setAttribute("code", code);
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/engineerlistsTodo");
    }

    /**
     * 派单前检查条件
     *
     * @return
     */
    @RequestMapping(params = "SendSingleServiceBusiness")
    @ResponseBody
    public AjaxJson SendSingleServiceBusiness(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //服务单id
        String cbsServiceId = request.getParameter("cbsServiceId");
        //检查是否符合派单条件
        j = cbsServiceAssignListService.SendSingleServiceBusiness(cbsServiceId);
        if (j.isSuccess()) {
            //获取 巴可内部处理 的关于服务单所有处理内容
            String sql = "SELECT REPLACE(GROUP_CONCAT(description,';'),',', '') as con from cbs_handle_log WHERE log_type ='3' and business_id='" + cbsServiceId + "'";
            Map<String, Object> map = systemService.findOneForJdbc(sql);
            if (map.size() > 0) {
                j.setObj(map.get("con"));
            } else {
                j.setObj("");
            }
        }
        return j;
    }

    /**
     * HD派单给服务商
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "dosaveDispatch")
    @ResponseBody
    public AjaxJson dosaveDispatch(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String cbsServiceId = request.getParameter("cbsServiceId");//服务单id
        String contacterName = request.getParameter("contacterName");   //服务商接单人姓名
        String contacterEmail = request.getParameter("contacterEmail");   //服务商邮箱
        String authentication = request.getParameter("authentication"); //工程师级别
        String contacterCellPhone = request.getParameter("contacterCellPhone"); //服务商电话
        String assignDes = request.getParameter("assignDes"); //派单要求
        String handleDes = request.getParameter("handleDes"); //巴可400处理过程
        String contacterId = request.getParameter("contacterId");  //接单人id
        String company = request.getParameter("company"); //服务商code
        String attach = request.getParameter("attach");  //附加任务id
        TSUser user = ResourceUtil.getSessionUserName();

        //更新老单子，设置为以前的单子为服务商不可见
//        systemService.updateBySqlString("UPDATE cbs_service_assign_list set activity = '0' , `status` = '1' WHERE service_id = '" + cbsServiceId + "' AND activity = '1' AND assign_type = '1' AND assign_torole = '1'  and `status` != '1' and `status` != '2'");
        /*更新老单子，如果重新派单，将以前派过的历史流程全部删除*/
        systemService.updateBySqlString("DELETE FROM cbs_service_assign_list WHERE service_id = '" + cbsServiceId + "'");

        //根据服务商code ，获取服务商id
        TSDepart depart = systemService.findUniqueByProperty(TSDepart.class, "orgCode", company);
        CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, cbsServiceId);

        /*新建流转历史流程*/
        CbsServiceAssignListEntity cbsServiceAssignListEntity = new CbsServiceAssignListEntity();
        cbsServiceAssignListEntity.setServiceId(cbsServiceEntity);
        cbsServiceAssignListEntity.setAssignType(Integer.parseInt(StaticValue.assign_type_1));
        cbsServiceAssignListEntity.setServiceProviderId(null != depart ? depart.getId() : "");//服务商id
        cbsServiceAssignListEntity.setAssignTorole(Integer.parseInt(StaticValue.assign_torole_1)); //被指派人员角色
        cbsServiceAssignListEntity.setAssignDes(assignDes); //派单要求
        cbsServiceAssignListEntity.setStatus(0);//被派单
        cbsServiceAssignListEntity.setActivity(1);//是当前活动用户

        /*获取被指派人角色*/
        ZyContactsEntity zyContacts = systemService.get(ZyContactsEntity.class, contacterId);
        if (null != zyContacts) {
            cbsServiceEntity.setZyContacts(contacterId);
            cbsServiceEntity.setHandleDes(handleDes);
            List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", zyContacts.getTsBaseUser().getId());
            cbsServiceAssignListEntity.setAssignToroleId(roleUsers.get(0).getTSRole().getId());  //被指派的相关角色ID
            cbsServiceAssignListEntity.setAssignTouser(contacterId); //被指派人员ID，联系人id
        }
        systemService.saveOrUpdate(cbsServiceAssignListEntity);


        //修改服务单状态为处理中，服务单处理进度为已分派第三方
        if (StringUtil.isNotEmpty(cbsServiceEntity)) {
            cbsServiceEntity.setStatus(StaticValue.clz);
            cbsServiceEntity.setSpeedStatus(StaticValue.tfpdsf);
            cbsServiceEntity.setAssignTime(new Date());
            cbsServiceEntity.setServiceProviderCode(company);
            cbsServiceEntity.setAuthentication(authentication);
            cbsServiceEntity.setAssignDes(assignDes);
            cbsServiceEntity.setHdUser(user.getId()); //HD派单人id
            systemService.saveOrUpdate(cbsServiceEntity);
        }
        //拒绝成功后，将除了新建的日志之外，变为已拒绝，商务，区域工程师，以及工程师的日志不包含拒绝的
        cbsServiceLogServiceI.cbsServiceLog(cbsServiceId);

        //清空服务单的附加任务，再重新分配
        systemService.updateBySqlString("DELETE from `cbs_service_task_map` WHERE service_id='" + cbsServiceId + "'");
        if (StringUtil.isNotEmpty(attach)) { //附加任务id
            String[] str = attach.split(",");
            for (String s : str) {
                if (StringUtil.isNotEmpty(s)) {
                    CbsServiceTaskMapEntity cbsServiceTaskMapEntity = new CbsServiceTaskMapEntity();
                    CbsAttachTaskEntity cbsAttachTaskEntity = systemService.get(CbsAttachTaskEntity.class, s);
                    if (StringUtil.isNotEmpty(cbsAttachTaskEntity)) {
                        if (StringUtil.isNotEmpty(cbsAttachTaskEntity.getAssignmentTotal()) && cbsAttachTaskEntity.getAssignmentTotal() != 0) {
                            cbsAttachTaskEntity.setAssignmentTotal(cbsAttachTaskEntity.getAssignmentTotal() + 1);
                        } else {
                            cbsAttachTaskEntity.setAssignmentTotal(1);
                        }
                        systemService.saveOrUpdate(cbsAttachTaskEntity);
                        cbsServiceTaskMapEntity.setAttachTaskId(cbsAttachTaskEntity);
                    } else {
                        cbsServiceTaskMapEntity.setAttachTaskId(null);
                    }
                    cbsServiceTaskMapEntity.setServiceId(cbsServiceEntity);
                    cbsServiceTaskMapServiceI.saveOrUpdate(cbsServiceTaskMapEntity);
                }
            }
        }
        //服务单日志
        cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单已分派第三方服务商：" + contacterName, null);

        /**
         * 发送邮件给服务商维修商务
         */
        String level = cbsServiceEntity.getLevel();
        String type = "";
        if (StringUtil.isNotEmpty(cbsServiceEntity.getZyEquipmentSpareServiceId())) {
            type = cbsServiceEntity.getZyEquipmentSpareServiceId().getType().getTypeDesc();
        } else if (StringUtil.isNotEmpty(cbsServiceEntity.getZyEquipmentSpareId())) {
            type = cbsServiceEntity.getZyEquipmentSpareId().getType().getTypeDesc();
        }
        String serviceType = cbsServiceEntity.getServiceType2().getName();
        String code = cbsServiceEntity.getCode();
        String zyCinemaName = cbsServiceEntity.getZyCinemaName();
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");

        /*邮件*/
        //序列号
        String strSN =StringUtil.isNotEmpty(cbsServiceEntity.getSn()) ? cbsServiceEntity.getSn() : cbsServiceEntity.getSnServer();
        //保内/保外
        //List<String> listbySql = systemService.findListbySql("select date_format(repair_end_date,'%Y-%m-%d') from zy_equipment_spare where sn='" + strSN + "'");
        String description = cbsServiceEntity.getDescription().trim();
//        if (listbySql.size() > 0) {
//            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
//            String now = sdf2.format(new Date());
//            if (now.compareTo(listbySql.get(0).toString()) >= 0 ){
//                description = "设备保外。"+description;
//            } else {
//                description = "设备保内。"+description;
//            }
//        }

        ZyEmailEntity eMail = new ZyEmailEntity();
        String s = "巴可派单：" + level + "-" + serviceType + "-" + code + "-" + zyCinemaName + "-" + sdf.format(new Date()) + "";
        eMail.setEmailSubject(s);
        eMail.setEmailReceiver(contacterEmail);
        Map<String, Object> paraMap1 = new HashMap<String, Object>();
        paraMap1.put("contacterName", StringUtil.isNotEmpty(depart) ? depart.getShortname() : "");//服务单名称
        paraMap1.put("type", type);
        paraMap1.put("sn", strSN);
        paraMap1.put("description", description);
        paraMap1.put("level", level);
        paraMap1.put("authentication", cbsServiceEntity.getAuthentication());
        paraMap1.put("zyCinemaName", cbsServiceEntity.getZyCinemaName());
        paraMap1.put("zyContactsName", cbsServiceEntity.getContactsName());
        paraMap1.put("phone", cbsServiceEntity.getContactsPhone());
        if (StringUtil.isNotEmpty(contacterEmail)) {
            SendMailUtil.sendFtlMail(eMail, "mail_send_single_service_business.ftl", paraMap1, systemService);
        }

        /*短信*/
        Map<String, Object> paraMap = new HashMap<String, Object>();
        paraMap.put("contacterName", StringUtil.isNotEmpty(depart) ? depart.getShortname() : "");
        paraMap.put("code", code);
        paraMap.put("type", type);
        paraMap.put("sn", strSN);
        paraMap.put("zyCinemaName", cbsServiceEntity.getZyCinemaName());
        paraMap.put("zyContactsName", cbsServiceEntity.getContactsName());
        paraMap.put("phone", cbsServiceEntity.getContactsPhone());
        paraMap.put("description", description);
        paraMap.put("city", cbsServiceEntity.getProvince().getTerritoryName() + "-" + cbsServiceEntity.getCity().getTerritoryName());
        if (StringUtil.isNotEmpty(contacterCellPhone)) {
            String[] cons = contacterCellPhone.split("/");
            for (int i = 0; i < cons.length; i++) {
                SendMessage.sendSMSFTL(cons[i], "message_send_single_service_business.ftl", paraMap, systemService);
            }
        }

        //创建 APP消息
        CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
        String content = "您收到1个新的服务任务，可在“我的任务”中查看详情";
        appMessage.setContent(content);
        appMessage.setSender(user.getId());
        TSBaseUser baseUser = systemService.get(TSBaseUser.class, zyContacts.getTsBaseUser().getId());
        appMessage.setReciver(baseUser.getId());
        appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
        systemService.save(appMessage);
        systemService.addLog("新增APP消息,接受方:" + baseUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);

        //定时任务，发送邮件
        if (StringUtil.isNotEmpty(cbsServiceEntity)) {
            assignStatus(cbsServiceEntity.getId(), depart.getShortname(), contacterEmail, contacterCellPhone, level, serviceType, code, zyCinemaName);
        }

        j.setObj(code);
        j.setSuccess(true);
        j.setMsg("服务单派单成功！");

        return j;
    }


    /*HD派单服务商商务后1小时（该时限可人为设置），服务商没有拒绝也没有派单给区域工程师或工程师，邮件提醒HD主管和服务商商务*/
    public void assignStatus(final String id, final String contacterName, final String contacterEmail, final String contacterCellPhone, final String level, final String serviceType, final String code, final String zyCinemaName) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
                if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyfp)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                    /*服务商商务*/
                    /*邮件*/
                    ZyEmailEntity eMail = new ZyEmailEntity();
                    String s = "巴可服务单超时提醒：" + contacterName + "-" + level + "-" + serviceType + "-" + code + "-" + zyCinemaName + "-" + sdf.format(new Date()) + "";
                    eMail.setEmailSubject(s);
                    eMail.setEmailReceiver(contacterEmail);
                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                    paraMap1.put("code", code);
                    if (StringUtil.isNotEmpty(contacterEmail)) {
                        SendMailUtil.sendFtlMail(eMail, "mail_send_single_service_business_host.ftl", paraMap1, systemService);
                    }
                    /*短信*/
                    Map<String, Object> paraMap = new HashMap<String, Object>();
                    paraMap.put("code", code);
                    if (StringUtil.isNotEmpty(contacterCellPhone)) {
                        String[] cons = contacterCellPhone.split("/");
                        SendMessage.sendSMSFTL(cons[0], "message_send_single_service_business_host.ftl", paraMap, systemService);
                    }

                    /*HD主管*/
                    /*邮件*/
                    List<TSRoleUser> roleUsers = systemService.findHql("from TSRoleUser where TSRole.roleCode=?", StaticValue.RULE_CODE_BARCO_HD_Manager);
                    for (TSRoleUser tr : roleUsers) {
                        if (tr.getTSUser() != null && StringUtil.isNotEmpty(tr.getTSUser().getEmail())) {
                            if (tr.getTSUser().getStatus().equals(Globals.User_Normal)) {
                                logger.info("发送邮件至：" + tr.getTSUser().getEmail());
                                ZyEmailEntity eMail1 = new ZyEmailEntity();
                                String s1 = "巴可服务单超时提醒：" + contacterName + "-" + level + "-" + serviceType + "-" + code + "-" + zyCinemaName + "-" + sdf.format(new Date()) + "";
                                eMail1.setEmailSubject(s1);
                                eMail1.setEmailReceiver(tr.getTSUser().getEmail());
                                if (StringUtil.isNotEmpty(tr.getTSUser().getEmail())) {
                                    SendMailUtil.sendFtlMail(eMail1, "mail_send_single_service_business_host.ftl", paraMap1, systemService);
                                }
                                /*短信*/
                                //SendMessage.sendSMSFTL("18600636618", "message_send_single_service_business_host.ftl", paraMap, systemService);
                            }
                        }
                    }
                }
            }
        }, StaticValue.assignStatusTiem);
    }


    /**
     * 商务任务列表
     *
     * @param
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "facilitator")
    public void facilitator(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        /*try {
            Set set = new HashSet();
            Map param = new HashMap<>();
            String speedstatus1 = request.getParameter("speedstatus1");
            //获取当前用户角色
            TSUser user = ResourceUtil.getSessionUserName();
            //判断当前用户是否是服务商商务
            List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where tsBaseUser.id = ?", user.getId());
            if (zyContactsEntities.size() > 0) {

                StringBuffer sb = new StringBuffer();
                sb.append("select service_id from CBS_SERVICE_ASSIGN_LIST ");
                sb.append("WHERE assign_touser =?");  //接单人id为当前用户id
                sb.append(" and `status` != 1 and `status` != 2 "); //不查找派给同级区域工程师的单子
                sb.append(" and assign_torole='1' "); //派给商务的单子

                for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                    List<Map<String, Object>> cbsServiceAssignList = systemService.findForJdbc(sb.toString(), zyContactsEntity.getId());
                    if (cbsServiceAssignList.size() > 0) {
                        for (Map<String, Object> stringObjectMap : cbsServiceAssignList) {
                            set.add(stringObjectMap.get("service_id"));
                        }
                    }
                }
            }

            if (set.size() > 0) {
                param.put("service_id", set.toArray());
            } else {
                param.put("service_id", "");
            }

            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_begin")))) {
                param.put("assignTime_begin", oConvertUtils.getString(param.get("assignTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_end")))) {
                param.put("assignTime_end", oConvertUtils.getString(param.get("assignTime_end")) + " 23:59:59");
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[]   speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }

            System.out.println("商务列表查询的param=" + com.alibaba.fastjson.JSONObject.toJSONString(param));
            wiseCoreService.selectDataGrid("selectSWserviceDatagrid", param, dataGrid);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);*/

        /*-- update by X on 20190801*/
        try {
            cbsServiceAssignListService.queryFacilitatorData(request, response, dataGrid);
            TagUtil.datagrid(response, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        /*-- update by X on 20190801 -- end */
    }

    /**
     * 商务任务待办列表
     *
     * @param
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "facilitatorTodo")
    public void facilitatorTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Set set = new HashSet();
            Map param = new HashMap<>();
            String speedstatus1 = request.getParameter("speedstatus1");
            //获取当前用户角色
            TSUser user = ResourceUtil.getSessionUserName();
            //判断当前用户是否是服务商商务
            List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where tsBaseUser.id = ?", user.getId());
            if (zyContactsEntities.size() > 0) {
                for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                    StringBuffer sb = new StringBuffer();
                    sb.append("select service_id from CBS_SERVICE_ASSIGN_LIST ");
                    sb.append("WHERE assign_touser =?");  //接单人id为当前用户id
                    sb.append(" and `status` != 1 and `status` != 2 "); //不查找派给同级区域工程师的单子
                    sb.append(" and assign_torole='1' "); //派给商务的单子
                    List<Map<String, Object>> cbsServiceAssignList = systemService.findForJdbc(sb.toString(), zyContactsEntity.getId());
                    if (cbsServiceAssignList.size() > 0) {
                        for (Map<String, Object> stringObjectMap : cbsServiceAssignList) {
                            set.add(stringObjectMap.get("service_id"));
                        }
                    }
                }
            }

            if (set.size() > 0) {
                List<String> listbySql = systemService.findListbySql("select id from zy_contacts where base_id='" + user.getId() + "'");
                param.put("zyContacts", listbySql.get(0));
            }

            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_begin")))) {
                param.put("assignTime_begin", oConvertUtils.getString(param.get("assignTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_end")))) {
                param.put("assignTime_end", oConvertUtils.getString(param.get("assignTime_end")) + " 23:59:59");
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[] speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }
            wiseCoreService.selectDataGrid("selectSWserviceTodoDatagrid", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 商务转派页面跳转
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "findEngineerPeopleList")
    public ModelAndView findEngineerPeopleList(HttpServletRequest request) {
        //需要分配的任务个数
        String planIds = oConvertUtils.getString(request.getParameter("planIds"));
        if (StringUtil.isNotEmpty(planIds)) {
            request.setAttribute("planIds", planIds);
            String[] ids = planIds.split(",");
            if (ids != null && ids.length > 0) {
                if (StringUtil.isNotEmpty(ids[0])) {
                    List<Map<String, Object>> list = systemService.findForJdbc("SELECT service_provider_code FROM cbs_service WHERE id = '" + ids[0].toString() + "'");
                    request.setAttribute("companyCode", list.get(0).get("service_provider_code")); //第三方服务商
                    request.setAttribute("planIdsArrsize", ids.length);
                }
            }
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/findEngineerPeople");
    }

    /**
     * 区域工程师任务列表
     *
     * @param
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "facilitators")
    public void facilitators(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Set set = new HashSet();
            Map param = new HashMap<>();
            String speedstatus1 = request.getParameter("speedstatus1");
            TSUser user = ResourceUtil.getSessionUserName();
            List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
            if (null != egs && egs.size() > 0) {
            	param.put("engId", egs.get(0).getId());
            } else {
            	param.put("engId", "");
            }

            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_begin")))) {
                param.put("assignTime_begin", oConvertUtils.getString(param.get("assignTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_end")))) {
                param.put("assignTime_end", oConvertUtils.getString(param.get("assignTime_end")) + " 23:59:59");
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[] speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }
            wiseCoreService.selectDataGrid("selectQYserviceDatagrid", param, dataGrid);

            //查询 关联所需要的 省市、工程师、服务类型
            List<Map<String,Object>> regioniMapList = systemService.findForJdbc("select id, territoryname from t_s_territory");
            List<Map<String,Object>> serviceTypeMapList = systemService.findForJdbc("select id, name from cbs_service_type");
            List<Map<String,Object>> deliverMapList = systemService.findForJdbc("select IFNULL(GROUP_CONCAT(expecttime SEPARATOR '\\\\'),'') AS expecttime, cr_code from CBS_DELIVER group by cr_code");

            Map<String, Map> regionMap = StringUtil.listToMapWithKey(regioniMapList, "id");
            Map<String, Map> serviceTypeMap = StringUtil.listToMapWithKey(serviceTypeMapList, "id");
            Map<String, Map> deliverMap = StringUtil.listToMapWithKey(deliverMapList, "cr_code");

            Iterator it = dataGrid.getResults().iterator();
            while(it.hasNext()){
                /**
                 *
                 cbs.PROVINCE,
                 cbs.city,
                 cbs.engineer_id,
                 cbs.service_type_2
                 */
                //替换、翻译数据库字段供页面展示
                Map<String, Object> m = (Map<String, Object>)it.next();
                if (StringUtil.isNotEmpty(m.get("provinces"))) {
                    m.put("provinces", regionMap.get(m.get("provinces").toString()).get("territoryname"));
                }
                if (StringUtil.isNotEmpty(m.get("city"))) {
                    m.put("city", regionMap.get(m.get("city").toString()).get("territoryname"));
                }
                if (StringUtil.isNotEmpty(m.get("servicetype"))) {
                    m.put("servicetype", serviceTypeMap.get(m.get("servicetype").toString()).get("name"));
                }
                if (StringUtil.isNotEmpty(m.get("code")) && null != deliverMap) {
                	if (deliverMap.get(m.get("code").toString()) != null) {
                		m.put("expecttime", deliverMap.get(m.get("code").toString()).get("expecttime"));
                	}
                }
            }
            
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 区域工程师待办任务列表
     *
     * @param
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "facilitatorsTodo")
    public void facilitatorsTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Set set = new HashSet();
            Map param = new HashMap<>();
            String speedstatus1 = request.getParameter("speedstatus1");
            TSUser user = ResourceUtil.getSessionUserName();
            List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
            if (null != egs && egs.size() > 0) {
                StringBuffer sb = new StringBuffer();
                sb.append("select service_id from CBS_SERVICE_ASSIGN_LIST ");
                sb.append("WHERE assign_touser =?");  //接单人id为当前用户id
                sb.append(" and `status` != 1  and `status` != 2 "); //不查找派给同级区域工程师的单子
                sb.append(" and assign_torole='2'"); //派给区域工程师的单子
                List<Map<String, Object>> cbsServiceAssignList = systemService.findForJdbc(sb.toString(), egs.get(0).getId());
                if (cbsServiceAssignList.size() > 0) {
                    for (Map<String, Object> stringObjectMap : cbsServiceAssignList) {
                        set.add(stringObjectMap.get("service_id"));
                    }
                }
                if (set.size() > 0) {
                    List<String> listbySql = systemService.findListbySql("select id from zy_engineer where ts_base_user_id='" + user.getId() + "'");
                    param.put("areaEngineer", listbySql.get(0));
                }
            }

            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_begin")))) {
                param.put("assignTime_begin", oConvertUtils.getString(param.get("assignTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_end")))) {
                param.put("assignTime_end", oConvertUtils.getString(param.get("assignTime_end")) + " 23:59:59");
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[] speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }
            wiseCoreService.selectDataGrid("selectQYserviceTodoDatagrid", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 区域工程师转派页面跳转
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "findArgEngineerPeopleList")
    public ModelAndView findArgEngineerPeopleList(HttpServletRequest request) {
        //需要分配的任务个数
        String planIds = oConvertUtils.getString(request.getParameter("planIds"));
        if (StringUtil.isNotEmpty(planIds)) {
            request.setAttribute("planIds", planIds);
            String[] ids = planIds.split(",");
            if (ids != null && ids.length > 0) {
                if (StringUtil.isNotEmpty(ids[0])) {
                    List<Map<String, Object>> list = systemService.findForJdbc("SELECT service_provider_code FROM cbs_service WHERE id = '" + ids[0].toString() + "'");
                    request.setAttribute("companyCode", list.get(0).get("service_provider_code")); //第三方服务商
                    request.setAttribute("planIdsArrsize", ids.length);
                }
            }
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/findArgEngineerPeople");
    }

    /**
     * 工程师转派页面跳转
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "findPeopleList")
    public ModelAndView findPeopleList(HttpServletRequest request) {
        //需要分配的任务个数
        String planIds = oConvertUtils.getString(request.getParameter("planIds"));
        if (StringUtil.isNotEmpty(planIds)) {
            String[] planIdsArr = planIds.split(",");
            request.setAttribute("planIds", planIds);
            String[] ids = planIds.split(",");
            if (ids != null && ids.length > 0) {
                if (StringUtil.isNotEmpty(ids[0])) {
                    List<Map<String, Object>> list = systemService.findForJdbc("SELECT service_provider_code FROM cbs_service WHERE id = '" + ids[0].toString() + "'");
                    request.setAttribute("companyCode", list.get(0).get("service_provider_code")); //第三方服务商
                    request.setAttribute("planIdsArrsize", ids.length);
                }
            }
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/findPeople");
    }

    /**
     * 商务拒绝任务
     *
     * @param
     * @return
     */
    @RequestMapping(params = "refuseEngineerPeopleList")
    public ModelAndView refuseEngineerPeopleList(HttpServletRequest req) {
        String planIds = req.getParameter("planIds");
        req.setAttribute("planIds", planIds);
        return new ModelAndView("com/zybk/cbsserviceassignlist/refuseEngineerPeople");
    }

    /**
     * 商务拒绝
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "refuseengineerassign")
    @ResponseBody
    public AjaxJson refuseEngineerPeople(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String planIds = request.getParameter("planIds");
        String reason = request.getParameter("reason");
        if (StringUtil.isNotEmpty(planIds)) {
            String[] planId = planIds.split(",");
            for (String s : planId) {
                CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, s);
                if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                    String id = cbsServiceEntity.getId();
                    systemService.updateBySqlString("UPDATE cbs_service_assign_list set `status` = '2',activity = '0',operation_des = '" + (StringUtil.isNotEmpty(reason) ? reason : "") + "'  WHERE service_id = '" + id + "' and assign_torole !=1"); /*and activity = 1*/
                    systemService.updateBySqlString("UPDATE cbs_service_assign_list SET activity = '1' WHERE service_id = '" + id + "' AND assign_torole = '1' AND assign_type = '1' AND `status` != '1' AND `status` != '2' ORDER BY create_date DESC LIMIT 1"); /*将商务的单子重新变为活动单*/
                    //修改服务单第三方状态为第三方已拒绝
                    cbsServiceEntity.setSpeedStatus(StaticValue.dsfyjj);
                    //修改服务单状态为第三方已受理
                    cbsServiceEntity.setStatus(StaticValue.ysl);
                    cbsServiceEntity.setEngineer("");
                    cbsServiceEntity.setAreaEngineer("");
                    systemService.saveOrUpdate(cbsServiceEntity);

                    //给HD派单人发送邮件
                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                    String serviceType = cbsServiceEntity.getServiceType2().getName();
                    TSDepart depart = systemService.findUniqueByProperty(TSDepart.class, "orgCode", cbsServiceEntity.getServiceProviderCode());
                    ZyContactsEntity contacts = systemService.get(ZyContactsEntity.class, cbsServiceEntity.getZyContacts());
                    TSUser user = systemService.get(TSUser.class, cbsServiceEntity.getHdUser());  /*HD派单人*/
                    String subject = "服务商拒单通知：" + depart.getShortname() + "-" + cbsServiceEntity.getLevel() + "-" + serviceType + "-" + cbsServiceEntity.getCode() + "-" + cbsServiceEntity.getZyCinemaName() + "-" + sdf.format(new Date());
                    ZyEmailEntity eMail = new ZyEmailEntity();
                    eMail.setEmailSubject(subject);
                    eMail.setEmailReceiver(StringUtil.isNotEmpty(user.getEmail()) ? user.getEmail() : "");
                    Map<String, Object> param = new HashMap<>();//参数
                    param.put("code", cbsServiceEntity.getCode());
                    param.put("reason", reason);
                    param.put("name", contacts.getName());
                    param.put("phone", contacts.getCellphone1());
                    if (StringUtil.isNotEmpty(user.getEmail())) {
                        SendMailUtil.sendFtlMail(eMail, "mail_hd_refuse_service.ftl", param, systemService);
                    }
                    /*短信*/
                    Map<String, Object> paraMap = new HashMap<String, Object>();
                    paraMap.put("code", cbsServiceEntity.getCode());
                    paraMap.put("reason", reason);
                    if (StringUtil.isNotEmpty(user.getMobilePhone())) {
                        SendMessage.sendSMSFTL(user.getMobilePhone(), "message_hd_refuse_service.ftl", paraMap, systemService);
                    }
                    //定时任务
                    refuseStatus(cbsServiceEntity.getId(), reason);
                    ajaxJson.setMsg("商务拒绝成功！");
                    //服务单日志
                    cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单被拒绝" + ((StringUtil.isNotEmpty(reason)) ? "原因:" + reason : ""), null);

                } else {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("拒绝失败！");
                }
            }
        } else {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("拒绝失败！");
        }


        return ajaxJson;
    }

    /*服务商商务拒单后5分钟，没有再次派单（即服务商处理进度仍为“服务商已拒绝”），向HD主管发送短信提醒*/
    public void refuseStatus(final String id, final String reason) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
                if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyjj)) {
                    //HD主管
                    List<TSRoleUser> roleUsers = systemService.findHql("from TSRoleUser where TSRole.roleCode=?", StaticValue.RULE_CODE_BARCO_HD_Manager);
                    for (TSRoleUser tr : roleUsers) {
                        if (StringUtil.isNotEmpty(tr.getTSUser()) && tr.getTSUser().getStatus().equals(Globals.User_Normal)) {
                            if (tr.getTSUser() != null && StringUtil.isNotEmpty(tr.getTSUser().getMobilePhone())) {  //用户状态为正常的
                                /*短信*/
                                Map<String, Object> paraMap = new HashMap<String, Object>();
                                paraMap.put("code", cbsServiceEntity.getCode());
                                paraMap.put("reason", reason);
                                SendMessage.sendSMSFTL(tr.getTSUser().getMobilePhone(), "message_hd_refuse_service_ds.ftl", paraMap, systemService);
                            }
                        }
                    }
                }
            }
        }, StaticValue.refuseStatusTiem);
    }


    /*检查商务能否派单*/
    @RequestMapping(params = "inspect")
    @ResponseBody
    public AjaxJson inspect(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        for (String id : planIds.split(",")) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
            if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyjj)) {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("服务单已经被拒绝不能派单！");
                break;
            }
            if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsssz)
                    || cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc)) {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("服务单不能进行派单！");
                break;
            }
        }
        return ajaxJson;
    }

    /*检查商务能否拒绝 inspectRefuse*/
    @RequestMapping(params = "inspectRefuse")
    @ResponseBody
    public AjaxJson inspectRefuse(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        for (String id : planIds.split(",")) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
            if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                //巴可派单40分钟后不能拒绝
                Date date = new Date();
                int minutes = (int) ((date.getTime() - cbsServiceEntity.getAssignTime().getTime()) / (1000 * 60));
                if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc)) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("服务已完成，不能拒单！");
                    break;
                } else if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyjj)) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("第三方已拒绝，不能重复操作！");
                    break;
                } else if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsssz)) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("工程师实施中，不能拒绝！");
                    break;
                } else if (minutes > 40) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("派单时间超过40分钟，拒单失败！");
                    break;
                }
            }
        }
        return ajaxJson;
    }

    /**
     * 商务转派
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "findEngineerPeople")
    @ResponseBody
    public AjaxJson findEngineerPeople(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();

        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        String providerId = oConvertUtils.getString(request.getParameter("providerId"));//服务商id
        String assignTouserId = oConvertUtils.getString(request.getParameter("assignTouserId")); //接单人id
        String assignToroleId = oConvertUtils.getString(request.getParameter("assignToroleId")); //接单人角色id
        String assignTorole = oConvertUtils.getString(request.getParameter("assignTorole")); //接单人角色名称
        String reason = oConvertUtils.getString(request.getParameter("reason"));  /*派单备注*/

        if (StringUtil.isNotEmpty(planIds)) {
            String[] planIdsArr = planIds.split(",");
            request.setAttribute("planIds", planIds);
            request.setAttribute("planIdsArrsize", planIdsArr.length);
            for (String id : planIdsArr) {
                TSUser user = ResourceUtil.getSessionUserName();
                CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
                boolean flag = true;
                if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyjj)) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("服务单已经被拒绝不能转派");
                    flag = false;
                }
                if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsssz)
                        || cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc)) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("服务单不能进行转派！");
                    flag = false;
                } else if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyfp)) { //第三方已分配状态，只能分派给下级，不能分配给同级
                    if (assignTorole.equals(StaticValue.RULE_CODE_THIRDPARTY_HEADER)) {  //商务派单给商务
                        ajaxJson.setSuccess(false);
                        ajaxJson.setMsg("服务单不能转派给同级人员！");
                        flag = false;
                    }
                }

                if (flag) {
                    List<CbsServiceAssignListEntity> cbsServiceAssignListEntities = systemService.findHql("from CbsServiceAssignListEntity where serviceId.id = ? and activity = ? ", id, 1);
                    if (cbsServiceAssignListEntities.size() > 0) {
                        for (CbsServiceAssignListEntity cbsServiceAssignListEntity : cbsServiceAssignListEntities) {
                            /*短信和APP参数*/
                            Map<String, Object> paraMap = new HashMap<String, Object>();
                            TSBaseUser baseUser = null;
                            try {
                                boolean fal = true;
                                CbsServiceAssignListEntity cbsServiceAssignListEntity1 = new CbsServiceAssignListEntity();

                                if (assignTorole.equals(StaticValue.RULE_CODE_THIRDPARTY_HEADER)) {  //商务派单给商务
                                    TSDepart tsDepart = systemService.get(TSDepart.class, providerId);
                                    cbsServiceEntity.setServiceProviderCode(StringUtil.isNotEmpty(tsDepart) ? tsDepart.getOrgCode() : ""); //修改服务单商务code
                                    cbsServiceEntity.setSpeedStatus(StaticValue.tfpdsf);
                                    cbsServiceEntity.setOrderTimeAgin(null);
                                    cbsServiceEntity.setOrderTime(null);
                                    cbsServiceEntity.setDoorNumber(0);
                                    cbsServiceEntity.setZyContacts(assignTouserId);
                                    systemService.saveOrUpdate(cbsServiceEntity);

                                    cbsServiceAssignListEntity1.setServiceId(cbsServiceEntity);
                                    cbsServiceAssignListEntity1.setAssignType(Integer.parseInt(StaticValue.assign_type_1));
                                    cbsServiceAssignListEntity1.setAssignTorole(Integer.parseInt(StaticValue.assign_torole_1)); //被指派人员角色
                                    //老单子，修改状态
                                    if (StringUtil.isNotEmpty(cbsServiceAssignListEntity)) {
                                        cbsServiceAssignListEntity.setStatus(1);//同级已转派，此单不可见
                                        cbsServiceAssignListEntity.setActivity(0);//不是当前活动用户
                                        systemService.saveOrUpdate(cbsServiceAssignListEntity);
                                    }

                                    ZyContactsEntity zyContactsEntity = systemService.get(ZyContactsEntity.class, assignTouserId);
                                    cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单发生同级商务转派," + (StringUtil.isNotEmpty(user.getRealName()) ? "给" + zyContactsEntity.getName() : "") + (StringUtil.isNotEmpty(reason) ? ("备注：" + reason) : ""), null);

                                    paraMap.put("contacterCellPhone", zyContactsEntity.getCellphone1());  /*短信参数*/
                                    paraMap.put("zyContactsName", zyContactsEntity.getName());  /*短信参数*/
                                    paraMap.put("zyContactsMail", zyContactsEntity.getEmail());  /*邮件参数*/
                                    baseUser = systemService.get(TSBaseUser.class, zyContactsEntity.getTsBaseUser().getId());
                                } else if (assignTorole.equals(StaticValue.RULE_CODE_AREA_ENGINEER)) { //商务派单给区域工程师

                                    if (StringUtil.isNotEmpty(cbsServiceAssignListEntity)) {
                                        //老单子，修改状态
                                        if (cbsServiceAssignListEntity.getAssignTorole() == 3) {
                                            //如果服务单派单给工程师后，第三方状态是第三方已分配，，则说明，该单是直接派给工程师的单子
                                            if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.dsfyfp)) {
                                                ajaxJson.setSuccess(false);
                                                ajaxJson.setMsg("服务单直接分配给工程师的，不能再分配给区域工程师！");
                                                fal = false;

                                            } else {
                                                // 判断活动单子，是否已经派给的工程师，如果是，查找服务单所有的派单信息，删除
                                                systemService.updateBySqlString("DELETE FROM cbs_service_assign_list WHERE service_id = '" + id + "' and assign_torole !=1");
                                            }
                                        } else if (cbsServiceAssignListEntity.getAssignTorole() == 2) {
                                            // 判断活动单子，是否是派给的区域工程师，如果是，同级不可见
                                            cbsServiceAssignListEntity.setStatus(1);//将上一个派给区域的单子，至为同级，上一条线的区域不可见
                                            cbsServiceAssignListEntity.setActivity(0);//不是当前活动用户
                                            systemService.saveOrUpdate(cbsServiceAssignListEntity);
                                        } else {
                                            cbsServiceAssignListEntity.setStatus(4);
                                            cbsServiceAssignListEntity.setActivity(0);//不是当前活动用户
                                            systemService.saveOrUpdate(cbsServiceAssignListEntity);
                                        }
                                    }
                                    if (fal) {
                                        cbsServiceAssignListEntity1.setServiceId(cbsServiceEntity);
                                        cbsServiceAssignListEntity1.setAssignType(Integer.parseInt(StaticValue.assign_type_3));
                                        cbsServiceAssignListEntity1.setAssignTorole(Integer.parseInt(StaticValue.assign_torole_2)); //被指派人员角色
                                        cbsServiceEntity.setSpeedStatus(StaticValue.dsfyfp); //第三方处理进度为第三方已分配
                                        cbsServiceEntity.setAreaEngineer(assignTouserId);
                                        systemService.saveOrUpdate(cbsServiceEntity);

                                        ZyEngineerEntity zyEngineerEntities = systemService.getEntity(ZyEngineerEntity.class, assignTouserId);
                                        cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单已分派第三方区域工程师：" + zyEngineerEntities.getName() + (StringUtil.isNotEmpty(reason) ? ("。备注：" + reason) : ""), null);
                                        paraMap.put("contacterCellPhone", zyEngineerEntities.getCellphone());  /*短信参数*/
                                        paraMap.put("zyContactsName", zyEngineerEntities.getName());  /*短信参数*/
                                        paraMap.put("zyContactsMail", zyEngineerEntities.getEmail());  /*邮件参数*/
                                        baseUser = systemService.get(TSBaseUser.class, zyEngineerEntities.getTsBaseUser().getId());
                                    }


                                } else if (assignTorole.equals(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER)) {  //商务派单给工程师
                                    //商务派给工程师，
                                    systemService.updateBySqlString("DELETE FROM cbs_service_assign_list WHERE service_id = '" + id + "' and assign_torole !=1");

                                    //老单子，修改状态
                                    List<CbsServiceAssignListEntity> cbsServiceAssignListEntities1 = systemService.findHql("from CbsServiceAssignListEntity where serviceId.id = ? and activity = ? ", id, 1);
                                    if (StringUtil.isNotEmpty(cbsServiceAssignListEntities1) && cbsServiceAssignListEntities1.size() > 0) {
                                        cbsServiceAssignListEntity = cbsServiceAssignListEntities1.get(0);
                                        if (StringUtil.isNotEmpty(cbsServiceAssignListEntity)) {
                                            // 判断活动单子，是否是派给的区域工程师，如果是，同级不可见
                                            if (cbsServiceAssignListEntity.getAssignTorole() == 2) {
                                                cbsServiceAssignListEntity.setStatus(1);//将上一个派给商务的单子，至为同级，上一条线的商务不可见
                                            } else {
                                                cbsServiceAssignListEntity.setStatus(4);//派单给下级
                                            }
                                            cbsServiceAssignListEntity.setActivity(0);//不是当前活动用户
                                            systemService.saveOrUpdate(cbsServiceAssignListEntity);
                                        }
                                    }
                                    ZyEngineerEntity zyEngineerEntities = systemService.getEntity(ZyEngineerEntity.class, assignTouserId);

                                    if (StringUtil.isNotEmpty(zyEngineerEntities) && StringUtil.isNotEmpty(zyEngineerEntities.getParentId())) {
                                        ZyEngineerEntity zyEngineerParent = zyEngineerEntities.getParentId();
                                        //构造一条假数据，如果工程师有上级工程师，默认派单给区域工程师后，再派单给工程师
                                        CbsServiceAssignListEntity cbsServiceAssignListEntity2 = new CbsServiceAssignListEntity();
                                        cbsServiceAssignListEntity2.setServiceId(cbsServiceEntity);
                                        cbsServiceAssignListEntity2.setAssignType(Integer.parseInt(StaticValue.assign_type_3));
                                        cbsServiceAssignListEntity2.setAssignTorole(Integer.parseInt(StaticValue.assign_torole_2)); //被指派人员角色
                                        cbsServiceAssignListEntity2.setAssignToroleId(assignToroleId); //接单人的角色的id
                                        cbsServiceAssignListEntity2.setAssignDes(cbsServiceEntity.getAssignDes()); //派单要求
                                        cbsServiceAssignListEntity2.setStatus(4);//默认派单到下级
                                        cbsServiceAssignListEntity2.setActivity(0);//不是当前活动用户
                                        cbsServiceAssignListEntity2.setServiceProviderId(providerId);  //服务商id
                                        cbsServiceAssignListEntity2.setAssignTouser(zyEngineerParent.getId()); //接单人为区域工程师id
                                        cbsServiceAssignListEntity2.setMemo(reason); //备注
                                        cbsServiceAssignListEntity2.setCreateDate(new Date());
                                        cbsServiceAssignListEntity2.setCreateBy(user.getUserName());
                                        cbsServiceAssignListEntity2.setCreateName(user.getRealName());
                                        systemService.saveOrUpdate(cbsServiceAssignListEntity2);
                                        cbsServiceEntity.setAreaEngineer(zyEngineerParent.getId());
                                    }


                                    cbsServiceAssignListEntity1.setServiceId(cbsServiceEntity);
                                    cbsServiceAssignListEntity1.setAssignType(Integer.parseInt(StaticValue.assign_type_4));
                                    cbsServiceAssignListEntity1.setAssignTorole(Integer.parseInt(StaticValue.assign_torole_3)); //被指派人员角色
                                    cbsServiceEntity.setSpeedStatus(StaticValue.dsfyfp); //第三方处理进度为第三方已分配
                                    cbsServiceEntity.setEngineer(assignTouserId);
                                    cbsServiceEntity.setEngineerTime(new Date());
                                    systemService.saveOrUpdate(cbsServiceEntity);

                                    cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单已分派第三方工程师：" + zyEngineerEntities.getName() + (StringUtil.isNotEmpty(reason) ? ("。备注：" + reason) : ""), null);
                                    paraMap.put("contacterCellPhone", zyEngineerEntities.getCellphone());  /*短信参数*/
                                    paraMap.put("zyContactsName", zyEngineerEntities.getName());  /*短信参数*/
                                    paraMap.put("zyContactsMail", zyEngineerEntities.getEmail());  /*邮件参数*/
                                    baseUser = systemService.get(TSBaseUser.class, zyEngineerEntities.getTsBaseUser().getId());
                                }

                                if (fal) {
                                    cbsServiceAssignListEntity1.setAssignToroleId(assignToroleId); //接单人的角色的id
                                    cbsServiceAssignListEntity1.setAssignDes(cbsServiceEntity.getAssignDes()); //派单要求
                                    cbsServiceAssignListEntity1.setStatus(0);//被派单
                                    cbsServiceAssignListEntity1.setActivity(1);//是当前活动用户
                                    cbsServiceAssignListEntity1.setServiceProviderId(providerId);  //服务商id
                                    cbsServiceAssignListEntity1.setAssignTouser(assignTouserId); //接单人id
                                    cbsServiceAssignListEntity1.setMemo(reason); //备注
                                    cbsServiceAssignListEntity1.setCreateDate(new Date());
                                    cbsServiceAssignListEntity1.setCreateBy(user.getUserName());
                                    cbsServiceAssignListEntity1.setCreateName(user.getRealName());

                                    cbsServiceAssignListService.saveOrUpdate(cbsServiceAssignListEntity1);

                                    /*短信*/
                                    //SendMessage.sendSMSFTL(paraMap.get("contacterCellPhone").toString(), "message_send_swzp_service.ftl", paraMap, systemService);
                                    /*邮件*/
                                    String type = "";
                                    if (StringUtil.isNotEmpty(cbsServiceEntity.getZyEquipmentSpareServiceId())) {
                                        type = cbsServiceEntity.getZyEquipmentSpareServiceId().getType().getTypeDesc();
                                    } else if (StringUtil.isNotEmpty(cbsServiceEntity.getZyEquipmentSpareId())) {
                                        type = cbsServiceEntity.getZyEquipmentSpareId().getType().getTypeDesc();
                                    }
                                    TSDepart depart = systemService.findUniqueByProperty(TSDepart.class, "orgCode", cbsServiceEntity.getServiceProviderCode());
                                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                    ZyEmailEntity eMail = new ZyEmailEntity();
                                    String s = "巴可派单：" + cbsServiceEntity.getLevel() + "-" + cbsServiceEntity.getServiceType2().getName() + "-" + cbsServiceEntity.getCode() + "-" + cbsServiceEntity.getZyCinemaName() + "-" + sdf.format(new Date()) + "";
                                    eMail.setEmailSubject(s);
                                    eMail.setEmailReceiver(paraMap.get("zyContactsMail").toString());
                                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                    paraMap1.put("contacterName", StringUtil.isNotEmpty(depart) ? depart.getShortname() : "");//服务单名称
                                    paraMap1.put("type", type);
                                    paraMap1.put("sn", StringUtil.isNotEmpty(cbsServiceEntity.getSn()) ? cbsServiceEntity.getSn() : cbsServiceEntity.getSnServer());
                                    paraMap1.put("description", cbsServiceEntity.getDescription());
                                    paraMap1.put("level", cbsServiceEntity.getLevel());
                                    paraMap1.put("authentication", cbsServiceEntity.getAuthentication());
                                    paraMap1.put("zyCinemaName", cbsServiceEntity.getZyCinemaName());
                                    paraMap1.put("zyContactsName", cbsServiceEntity.getContactsName());
                                    paraMap1.put("phone", cbsServiceEntity.getContactsPhone());
                                    if (StringUtil.isNotEmpty(paraMap.get("zyContactsMail").toString())) {
                                        SendMailUtil.sendFtlMail(eMail, "mail_send_single_service_business.ftl", paraMap1, systemService);
                                    }
                                    /*APP*/
                                    CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
                                    String content = "您收到1个新的任务，具体内容请查看http://cbs.cfg-barco.com或登陆巴可客服App。";
                                    appMessage.setContent(content);
                                    appMessage.setSender(user.getId());
                                    appMessage.setReciver(baseUser.getId());
                                    appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                                    systemService.save(appMessage);
                                    systemService.addLog("新增APP消息,接受方:" + baseUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return ajaxJson;
    }


    /*检查区域工程师能否派单*/
    @RequestMapping(params = "inspectArgEng")
    @ResponseBody
    public AjaxJson inspectArgEng(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        for (String id : planIds.split(",")) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
            if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc) || cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsssz)) {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("服务单不符合派单条件！");
                break;
            }
        }
        return ajaxJson;
    }

    /**
     * 区域工程师转派
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "findArgEngineerPeople")
    @ResponseBody
    public AjaxJson findArgEngineerPeople(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();

        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        String providerId = oConvertUtils.getString(request.getParameter("providerId"));//服务商id
        String assignTouserId = oConvertUtils.getString(request.getParameter("assignTouserId")); //接单人id
        String assignToroleId = oConvertUtils.getString(request.getParameter("assignToroleId")); //接单人角色id
        String assignTorole = oConvertUtils.getString(request.getParameter("assignTorole")); //接单人角色名称
        String reason = request.getParameter("reason");
        if (StringUtil.isNotEmpty(planIds)) {
            ajaxJson = cbsServiceAssignListService.findArgEngineerPeople(planIds,providerId,assignTouserId,assignToroleId,assignTorole,reason);
        } else {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("区域工程师转派失败！");
        }
        return ajaxJson;
    }

    /**
     * 根据用户id获取联系人id，以及工程师任务未完成任务个数
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "getCompany")
    @ResponseBody
    public AjaxJson getCompany(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        String userId = request.getParameter("userId");
        String obj = request.getParameter("obj");

        //商务
        if (obj.equals("company") && StringUtil.isNotEmpty(userId)) {
            //商务角色，查找联系人信息
            ZyContactsEntity zyEngineer = systemService.get(ZyContactsEntity.class, userId);
            map.put("userPhone", zyEngineer.getCellphone1());
        }

        //区域工程师
        if (obj.equals("areaEngineer") && StringUtil.isNotEmpty(userId)) {
            /*区域或者工程师角色，查找工程师表信息*/
            ZyEngineerEntity zyEngineer = systemService.get(ZyEngineerEntity.class, userId);
            map.put("userPhone", zyEngineer.getCellphone());
        }

        //工程师任务状态下，未完成数量
        if (obj.equals("engineer") && StringUtil.isNotEmpty(userId)) {
            ZyEngineerEntity zyEngineer = systemService.get(ZyEngineerEntity.class, userId);
            map.put("userPhone", zyEngineer.getCellphone());
            List<Map<String, Object>> number = cbsServiceAssignListService.getNumberByUserId(userId);
            if (number.size() > 0) {
                map.put("num", number.get(0).get("num"));
            }
        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }


    /**
     * 工程师任务列表
     *
     * @param
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "facilitatorEng")
    public void facilitatorEng(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Set set = new HashSet();
            Map param = new HashMap<>();
            String speedstatus1 = request.getParameter("speedstatus1");
            //获取当前用户角色
            TSUser user = ResourceUtil.getSessionUserName();
            List<ZyEngineerEntity> zyEngineerEntities = systemService.findHql("from ZyEngineerEntity where tsBaseUser.id = ?", user.getId());
            if (zyEngineerEntities.size() > 0) {
                StringBuffer sb = new StringBuffer();
                sb.append("select service_id from CBS_SERVICE_ASSIGN_LIST ");
                sb.append("WHERE assign_touser =?");  //接单人id为当前用户id
                sb.append(" and `status` != 1  and `status` != 2 "); //不查找派给同级工程师的单子
                sb.append(" and assign_torole='3'"); //派给工程师的单子
                List<Map<String, Object>> cbsServiceAssignList = systemService.findForJdbc(sb.toString(), zyEngineerEntities.get(0).getId());
                if (cbsServiceAssignList.size() > 0) {
                    for (Map<String, Object> stringObjectMap : cbsServiceAssignList) {
                        set.add(stringObjectMap.get("service_id"));
                    }
                }
            }
            if (set.size() > 0) {
                param.put("service_id", set.toArray());
            } else {
                param.put("service_id", "");
            }

            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_begin")))) {
                param.put("assignTime_begin", oConvertUtils.getString(param.get("assignTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_end")))) {
                param.put("assignTime_end", oConvertUtils.getString(param.get("assignTime_end")) + " 23:59:59");
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[] speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }
            wiseCoreService.selectDataGrid("selectGCSserviceDatagrid", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 工程师待办任务列表
     *
     * @param
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "facilitatorEngTodo")
    public void facilitatorEngTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        try {
            Set set = new HashSet();
            Map param = new HashMap<>();
            String speedstatus1 = request.getParameter("speedstatus1");
            //获取当前用户角色
            TSUser user = ResourceUtil.getSessionUserName();
            List<ZyEngineerEntity> zyEngineerEntities = systemService.findHql("from ZyEngineerEntity where tsBaseUser.id = ?", user.getId());
            if (zyEngineerEntities.size() > 0) {
                StringBuffer sb = new StringBuffer();
                sb.append("select service_id from CBS_SERVICE_ASSIGN_LIST ");
                sb.append("WHERE assign_touser =?");  //接单人id为当前用户id
                sb.append(" and `status` != 1  and `status` != 2 "); //不查找派给同级工程师的单子
                sb.append(" and assign_torole='3'"); //派给工程师的单子
                List<Map<String, Object>> cbsServiceAssignList = systemService.findForJdbc(sb.toString(), zyEngineerEntities.get(0).getId());
                if (cbsServiceAssignList.size() > 0) {
                    for (Map<String, Object> stringObjectMap : cbsServiceAssignList) {
                        set.add(stringObjectMap.get("service_id"));
                    }
                }
            }
            if (set.size() > 0) {
                List<String> listbySql1 = systemService.findListbySql("select id from zy_engineer where ts_base_user_id='" + user.getId() + "'");
                param.put("engineer", listbySql1.get(0));
            }

            for (Object key : request.getParameterMap().keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_begin")))) {
                param.put("assignTime_begin", oConvertUtils.getString(param.get("assignTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("assignTime_end")))) {
                param.put("assignTime_end", oConvertUtils.getString(param.get("assignTime_end")) + " 23:59:59");
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[] speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }
            wiseCoreService.selectDataGrid("selectGCSserviceTodoDatagrid", param, dataGrid);

        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /*检查工程师能否派单*/
    @RequestMapping(params = "inspectEng")
    @ResponseBody
    public AjaxJson inspectEng(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        for (String id : planIds.split(",")) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
            if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsssz) || cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc)) {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("服务单不符合派单条件！");
                break;
            }
        }
        return ajaxJson;
    }

    /**
     * 工程师转派
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "findPeople")
    @ResponseBody
    public AjaxJson findPeople(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();

        String planIds = oConvertUtils.getString(request.getParameter("planIds")); //服务单的id
        String providerId = oConvertUtils.getString(request.getParameter("providerId"));//服务商id
        String assignTouserId = oConvertUtils.getString(request.getParameter("assignTouserId")); //接单人id
        String assignToroleId = oConvertUtils.getString(request.getParameter("assignToroleId")); //接单人角色id
        String assignTorole = oConvertUtils.getString(request.getParameter("assignTorole")); //接单人角色名称
        String reason = oConvertUtils.getString(request.getParameter("reason"));
        String typename = oConvertUtils.getString(request.getParameter("typename"));  //接单人的姓名
        if (StringUtil.isNotEmpty(planIds)) {
            String[] planIdsArr = planIds.split(",");
            request.setAttribute("planIds", planIds);
            for (String id : planIdsArr) {
                TSUser user = ResourceUtil.getSessionUserName();
                CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
                //如果工程师已接受的状态发生转派，则清空预约时间和预约次数
                if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsyjs)) {
                    cbsServiceEntity.setOrderTime(null);
                    cbsServiceEntity.setOrderTimeAgin(null);
                    cbsServiceEntity.setDoorNumber(0);
                    cbsServiceEntity.setSpeedStatus(StaticValue.qygcsyfp);
                }
                cbsServiceEntity.setEngineer(assignTouserId);
                systemService.saveOrUpdate(cbsServiceEntity);

                List<CbsServiceAssignListEntity> cbsServiceAssignListEntities = systemService.findHql("from CbsServiceAssignListEntity where serviceId.id = ? and activity = ? ", id, 1);
                if (cbsServiceAssignListEntities.size() > 0) {
                    CbsServiceAssignListEntity cbsServiceAssignListEntity = systemService.get(CbsServiceAssignListEntity.class, cbsServiceAssignListEntities.get(0).getId());
                    if (null != cbsServiceAssignListEntity) {
                        try {

                            CbsServiceAssignListEntity cbsServiceAssignListEntity1 = new CbsServiceAssignListEntity();
                            cbsServiceAssignListEntity1.setServiceId(cbsServiceEntity);
                            if (assignTorole.equals(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER)) {  //工程师派单给工程师
                                cbsServiceAssignListEntity1.setAssignType(Integer.parseInt(StaticValue.assign_type_4));
                                cbsServiceAssignListEntity1.setAssignTorole(Integer.parseInt(StaticValue.assign_torole_3)); //被指派人员角色
                                //老单子，修改状态
                                cbsServiceAssignListEntity.setStatus(1);//派单到同级
                                cbsServiceAssignListEntity.setActivity(0); //不是活动用户
                                cbsServiceAssignListEntity.setOperationDes(reason != null ? reason : ""); //原因

                                cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单发生同级工程师转派，给" + typename + (StringUtil.isNotEmpty(reason) ? ("原因：" + reason) : ""), null);

                            }

                            cbsServiceAssignListEntity1.setAssignToroleId(assignToroleId); //接单人的角色的id
                            cbsServiceAssignListEntity1.setAssignDes(cbsServiceAssignListEntity.getAssignDes()); //派单要求
                            cbsServiceAssignListEntity1.setStatus(0);//被派单
                            cbsServiceAssignListEntity1.setActivity(1);//是当前活动用户
                            cbsServiceAssignListEntity1.setServiceProviderId(providerId);  //服务商id
                            cbsServiceAssignListEntity1.setAssignTouser(assignTouserId); //接单人id
                            cbsServiceAssignListEntity1.setMemo(reason); //备注
                            cbsServiceAssignListEntity1.setCreateDate(new Date());
                            cbsServiceAssignListEntity1.setCreateBy(user.getUserName());
                            cbsServiceAssignListEntity1.setCreateName(user.getRealName());

                            cbsServiceAssignListService.saveOrUpdate(cbsServiceAssignListEntity1);

                            cbsServiceAssignListEntity.setActivity(0);//不是当前活动用户
                            systemService.saveOrUpdate(cbsServiceAssignListEntity);

                            /*短信*/
                            ZyEngineerEntity zyEngineerEntities = systemService.getEntity(ZyEngineerEntity.class, assignTouserId);
//                            Map<String, Object> paraMap = new HashMap<String, Object>();
//                            paraMap.put("contacterName", typename);
//                            SendMessage.sendSMSFTL(zyEngineerEntities.getCellphone(), "message_change_engservice.ftl", paraMap, systemService);
                            String level = cbsServiceEntity.getLevel();
                            String type = "";
                            if (StringUtil.isNotEmpty(cbsServiceEntity.getZyEquipmentSpareServiceId())) {
                                type = cbsServiceEntity.getZyEquipmentSpareServiceId().getType().getTypeDesc();
                            } else if (StringUtil.isNotEmpty(cbsServiceEntity.getZyEquipmentSpareId())) {
                                type = cbsServiceEntity.getZyEquipmentSpareId().getType().getTypeDesc();
                            }
                            String serviceType = cbsServiceEntity.getServiceType2().getName();
                            String code = cbsServiceEntity.getCode();
                            String zyCinemaName = cbsServiceEntity.getZyCinemaName();
                            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                            TSDepart depart = systemService.findUniqueByProperty(TSDepart.class, "orgCode", cbsServiceEntity.getServiceProviderCode());
                            /*邮件*/
                            ZyEmailEntity eMail = new ZyEmailEntity();
                            String s = "巴可派单：" + level + "-" + serviceType + "-" + code + "-" + zyCinemaName + "-" + sdf.format(new Date()) + "";
                            eMail.setEmailSubject(s);
                            eMail.setEmailReceiver(zyEngineerEntities.getEmail());
                            Map<String, Object> paraMap1 = new HashMap<String, Object>();
                            paraMap1.put("contacterName", StringUtil.isNotEmpty(depart) ? depart.getShortname() : "");//服务单名称
                            paraMap1.put("type", type);
                            paraMap1.put("sn", StringUtil.isNotEmpty(cbsServiceEntity.getSn()) ? cbsServiceEntity.getSn() : cbsServiceEntity.getSnServer());
                            paraMap1.put("description", cbsServiceEntity.getDescription());
                            paraMap1.put("level", level);
                            paraMap1.put("authentication", cbsServiceEntity.getAuthentication());
                            paraMap1.put("zyCinemaName", cbsServiceEntity.getZyCinemaName());
                            paraMap1.put("zyContactsName", cbsServiceEntity.getContactsName());
                            paraMap1.put("phone", cbsServiceEntity.getContactsPhone());
                            if (StringUtil.isNotEmpty(zyEngineerEntities.getEmail())) {
                                SendMailUtil.sendFtlMail(eMail, "mail_send_single_service_business.ftl", paraMap1, systemService);
                            }
//                            /*APP消息*/
                            CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
                            String content = "您收到1个新的任务，具体内容请查看http://cbs.cfg-barco.com或登陆巴可客服App。";
                            appMessage.setContent(content);
                            appMessage.setSender(user.getId());
                            TSBaseUser baseUser = systemService.get(TSBaseUser.class, zyEngineerEntities.getTsBaseUser().getId());
                            appMessage.setReciver(baseUser.getId());
                            appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                            systemService.save(appMessage);
                            systemService.addLog("新增APP消息,接受方:" + baseUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        ajaxJson.setSuccess(false);
                        ajaxJson.setMsg("工程师转派失败！");
                    }
                } else {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("工程师转派失败！");
                }
            }
        } else {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("工程师转派失败！");
        }
        return ajaxJson;
    }


    /**
     * @author xiul
     * 2016-10-27 下午1:50:08
     * Description 工程师预约上门时间 - 弹出页
     */
    @RequestMapping(params = "acceptanceService")
    public ModelAndView acceptanceService(HttpServletRequest req) {
        req.setAttribute("planIds", req.getParameter("planIds"));
        return new ModelAndView("com/zybk/cbsserviceassignlist/acceptance");
    }

    /*查找取消服务单条件能否取消*/
    @RequestMapping(params = "cancleService")
    @ResponseBody
    public AjaxJson cancleService(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //服务单id
        String cbsServiceId = request.getParameter("cbsServiceId");
        if (StringUtil.isNotEmpty(cbsServiceId)) {
            CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, cbsServiceId);
            if (cbsService.getSpeedStatus().equals(StaticValue.gcsssz) || cbsService.getSpeedStatus().equals(StaticValue.fwywc)) {
                j.setSuccess(false);
                j.setMsg("实施中和已完成的服务单不能取消！");
            }
            if (cbsService.getStatus().equals(StaticValue.yqx)) {
                j.setSuccess(false);
                j.setMsg("已取消的服务单不能多次取消！");
            }
            if (cbsService.getStatus().equals(StaticValue.ywc)) {
                j.setSuccess(false);
                j.setMsg("已完成的服务单不能取消！");
            }
        }
        return j;
    }

    /**
     * 编辑保存之前，派单是否能保存
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "updateService")
    @ResponseBody
    public AjaxJson updateService(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //服务单id
        String cbsServiceId = request.getParameter("cbsServiceId");
        if (StringUtil.isNotEmpty(cbsServiceId)) {
            CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, cbsServiceId);
            if (cbsService.getStatus().equals(StaticValue.ywc) || cbsService.getStatus().equals(StaticValue.yqx)) {
                j.setSuccess(false);
                j.setMsg("已取消和已完成的服务单不能编辑保存！");
            }
        }
        return j;
    }

    /**
     * PC端预约上门之前，判断服务单状态是否能预约上门
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "egAcceptAginTime")
    public AjaxJson egAcceptAginTime(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //服务单id
        String planIds = request.getParameter("planIds");
        if (StringUtil.isNotEmpty(planIds)) {
            for (String s : planIds.split(",")) {
                CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, s);
                if (cbsService.getDoorNumber() == null || StringUtil.isEmpty(cbsService.getDoorNumber().toString()) || cbsService.getDoorNumber() < 2) {
                    if (!cbsService.getSpeedStatus().equals(StaticValue.gcsyjs)) {
                        if (cbsService.getSpeedStatus().equals(StaticValue.gcsssz)) {
                            j.setSuccess(false);
                            j.setMsg("工程师实施中，不能再预约上门！");
                        } else if (cbsService.getSpeedStatus().equals(StaticValue.fwywc)) {
                            j.setSuccess(false);
                            j.setMsg("服务已完成，不能操作服务单！");
                        } else {
                            j.setSuccess(false);
                            j.setMsg("请先接受服务单，才能预约上门！");
                        }
                        break;
                    }
                } else {
                    j.setMsg("预约失败！最多只能修改两次预约上门时间！");
                    break;
                }
            }
        }
        return j;
    }

    /**
     * App 预约上门Time
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "appEgAcceptTime")
    public AjaxJson appEgAcceptTime(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String planIds = oConvertUtils.getString(request.getParameter("planIds"));
            String engineerOrderTime = oConvertUtils.getString(request.getParameter("engineerOrderTime")); //预约上门时间
            String remarks = oConvertUtils.getString(request.getParameter("remarks")); //预约上门备注
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            if (StringUtil.isNotEmpty(planIds)) {
                for (String s : planIds.split(",")) {
                    CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, s);
                    if (cbsServiceEntity.getDoorNumber() == null || StringUtil.isEmpty(cbsServiceEntity.getDoorNumber().toString()) || cbsServiceEntity.getDoorNumber() < 2) {
                        if (StringUtil.isNotEmpty(cbsServiceEntity.getDoorNumber()) && cbsServiceEntity.getDoorNumber() == 1) {
                            cbsServiceEntity.setDoorNumber(2);
                            cbsServiceEntity.setOrderTimeAgin(sf.parse(engineerOrderTime));
                            cbsServiceEntity.setRemarks(remarks);
                            //操作日志 第二次预约上门时间
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "工程师修改预约上门时间：" + engineerOrderTime + (StringUtil.isNotEmpty(remarks) ? ("。备注：" + remarks) : ""), null);

                        } else {
                            cbsServiceEntity.setDoorNumber(1);
                            cbsServiceEntity.setOrderTime(sf.parse(engineerOrderTime));
                            cbsServiceEntity.setRemarks(remarks);
                            //操作日志 第一次预约上门时间
                            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "工程师预约上门时间：" + engineerOrderTime + (StringUtil.isNotEmpty(remarks) ? ("。备注：" + remarks) : ""), null);

                        }
                        cbsServiceServiceI.save(cbsServiceEntity);
                        j.setMsg("预约成功！");

                    } else {
                        j.setMsg("预约失败！最多只能修改两次预约上门时间！");
                        break;
                    }
                }
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("预约失败");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @author xiul
     * 2016-4-12 上午11:22:40
     * Description 流程 - APP工程师接单
     */
    @ResponseBody
    @RequestMapping(params = "doBatchEngineerAppServicePlan")
    public AjaxJson doBatchEngineerAppServicePlan(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String planIds = oConvertUtils.getString(request.getParameter("planIds"));
            if (StringUtil.isNotEmpty(planIds)) {
                for (String s : planIds.split(",")) {
                    CbsServiceEntity cbsServiceEntity = cbsServiceServiceI.get(CbsServiceEntity.class, s);
                    if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsyjs)) {
                        j.setMsg("工程师已接受，不能重复操作！");
                        j.setSuccess(false);
                        break;
                    } else if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.gcsssz)) {
                        j.setMsg("工程师实施中，不能接受服务单！");
                        j.setSuccess(false);
                        break;
                    } else if (cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc)) {
                        j.setMsg("服务已完成,不能操作服务单！");
                        j.setSuccess(false);
                        break;
                    } else {
                        String sql = "UPDATE cbs_service s set s.`SPEED_STATUS`='" + StaticValue.gcsyjs + "' WHERE id = '" + s + "'";
                        systemService.updateBySqlString(sql);
                        //操作日志
                        cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "工程师接受任务", null);
                        j.setMsg("接受成功！");

                        ZyEngineerEntity zyEngineerEntities = systemService.getEntity(ZyEngineerEntity.class, cbsServiceEntity.getEngineer());
                        /*短信*/
                        Map<String, Object> paraMap = new HashMap<String, Object>();
                        paraMap.put("sn", cbsServiceEntity.getSn());
                        paraMap.put("code", cbsServiceEntity.getCode());
                        paraMap.put("name", zyEngineerEntities.getName());
                        paraMap.put("phone", zyEngineerEntities.getCellphone());
                        SendMessage.sendSMSFTL(cbsServiceEntity.getContactsPhone(), "message_eg_accept.ftl", paraMap, systemService);

                        //调用微信接口发送
                        List<TSUser> userList = systemService.findHql("from TSUser where mobilePhone=" + cbsServiceEntity.getContactsPhone());
                        List<Map<String, String>> list = new ArrayList<>();
                        String content = "尊敬的客户：您的放映机<" + cbsServiceEntity.getSn() + ">的服务申请<" + cbsServiceEntity.getCode() + ">已安排工程师为您服务。工程师< " + zyEngineerEntities.getName() + "><" + zyEngineerEntities.getCellphone() + ">将与您联系，请详细描述故障现象或服务要求，以便我们更准确地为您提供服务，谢谢！【中影巴可客服部】";
                        if (userList != null && userList.size() > 0) {
                            if (userList.get(0) != null && StringUtil.isNotEmpty(userList.get(0).getOpenId())) {
                                Map<String, String> map = new HashMap<>();
                                map.put("openid", userList.get(0).getOpenId());
                                map.put("message", content);
                                list.add(map);
                                wxCommonService.sendMsgForWx(list);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("接受失败");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 判断是否至少有一次上门签到的记录，以及服务单类型（根据服务单类型跳转不同的完工单页面）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "doorToDoorCheckIn")
    public AjaxJson DoorToDoorCheckIn(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String cbsId = request.getParameter("id");
        Map map = new HashMap();
        String type = "";
        if (StringUtil.isNotEmpty(cbsId)) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, cbsId);
            if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                if (StringUtil.isNotEmpty(cbsServiceEntity.getServiceType1()) && StringUtil.isNotEmpty(cbsServiceEntity.getServiceType2())) {
//                    List<ArrivalofabnormalEntity> arrivalofabnormalEntities = systemService.findByProperty(ArrivalofabnormalEntity.class, "serviceId.id", cbsId);
                    //判断是否是 现场检测 ，是现场检测的话，必须有一次上门签到类型
                    if (cbsServiceEntity.getServiceType1().getName().equals("服务支持") && cbsServiceEntity.getServiceType2().getName().equals("现场检测")) {
                        /*if (arrivalofabnormalEntities.size() == 0) {
                            ajaxJson.setMsg("至少有一次上门签到记录！");
                            ajaxJson.setSuccess(false);
                        } else {
                            type = "type-yj";
                        }*/
                        type = "type-yj";
                    } else if (cbsServiceEntity.getServiceType1().getName().equals("服务支持") && cbsServiceEntity.getServiceType2().getName().equals("维保检测")) {
                        type = "type-xcjc";
                    }
                    //引擎翻新业务(重写)
                    else if (cbsServiceEntity.getServiceType1().getName().equals("增值服务") && cbsServiceEntity.getServiceType2().getName().equals("引擎翻新")) {
                        type = "type-yqfxys";
                    }
                    /*光管翻新业务*/
                    else if (cbsServiceEntity.getServiceType1().getName().equals("增值服务") && cbsServiceEntity.getServiceType2().getName().equals("光管翻新")) {
                        type = "type-ggfx";
                    }
                    /*技术支持*/
                    else if (cbsServiceEntity.getServiceType1().getName().equals("服务支持") && cbsServiceEntity.getServiceType2().getName().equals("技术支持")) {
                        type = "type-jszc";
                    }
                    /*借用*/
                    else if (cbsServiceEntity.getServiceType1().getName().equals("服务支持") && cbsServiceEntity.getServiceType2().getName().equals("借用")) {
                        //创建发货单
                        type = "type-jy";
                    } else if (cbsServiceEntity.getServiceType1().getName().equals("故障维修")) {
                        type = "type-wx";
                    }
                }
                map.put("type", type);
                ajaxJson.setAttributes(map);
            }

        }
        return ajaxJson;
    }

    /**
     * 是否现场服务
     *
     * @return
     */
    @RequestMapping(params = "fieldservice")
    public ModelAndView fieldservice(HttpServletRequest request) {
        String cbsId = request.getParameter("id");
        request.setAttribute("cbsId", cbsId);
        return new ModelAndView("com/zybk/cbsserviceassignlist/fieldservice");
    }

    /**
     * 现场服务类型
     *
     * @return
     */
    @RequestMapping(params = "fieldDetectionType")
    public ModelAndView fieldDetectionType(HttpServletRequest request) {
        String cbsId = request.getParameter("id");
        request.setAttribute("cbsId", cbsId);
        return new ModelAndView("com/zybk/cbsserviceassignlist/fieldDetectionType");
    }

    /**
     * 商务角色服务单详情
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "detailsOfService")
    public ModelAndView detailsOfService(HttpServletRequest request) {
        TSUser user = ResourceUtil.getSessionUserName();
        String id = request.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {

            List<ZyContactsEntity> contactList = systemService.findHql("from ZyContactsEntity where tsBaseUser.id = ?", user.getId());

            //数据展示信息
            List<Map<String, Object>> cbsService = cbsServiceAssignListService.getDetailOfService(id, contactList.get(0).getId());
            request.setAttribute("cbsService", cbsService.get(0));

            //附加任务信息
            List<CbsServiceTaskMapEntity> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findByProperty(CbsServiceTaskMapEntity.class, "serviceId.id", id);
            request.setAttribute("cbsServiceTaskMap", cbsServiceTaskMap);

            //服务日志
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLogOfTp(id);
            request.setAttribute("cbsServiceLogList", cbsServiceLogList);

            //文件管理
            List<Map<String, Object>> zyFileLogEntity = cbsServiceAssignListService.getFileLogByServiceId(id, "A");
            request.setAttribute("zyFileLogEntityA", zyFileLogEntity);

            //获取申请的备件
            /*List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailList = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.serviceId='" + id + "'");
            if (cbsEquipmentApplyDetailList.size() > 0) {
                for (CbsEquipmentApplyDetailEntity cbsEquipmentApplyDetailEntity : cbsEquipmentApplyDetailList) {
                    List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where equipmentApplyDetailId.id='" + cbsEquipmentApplyDetailEntity.getId() + "'");
                    cbsEquipmentApplyDetailEntity.setCbsDeliverEquipmentEntityList(deliverEquipmentList);
                }
            }*/
            /*
             * 商务服务单详情中的备件申请列表
             * */
            List<Object[]> equipmentList = cbsServiceAssignListService.findEquipmentList(id);
            request.setAttribute("equipmentList", equipmentList);
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/CbsServiceDetialsOfTpAssignEngineer");
    }


    /**
     * 区域工程师角色服务单详情
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "detailsOfDistrictService")
    public ModelAndView detailsOfDistrictService(HttpServletRequest request) {
        TSUser user = ResourceUtil.getSessionUserName();
        String id = request.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            //数据展示信息
            ZyEngineerEntity engineer = systemService.findUniqueByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
            engineer = null == engineer ? new ZyEngineerEntity() : engineer;
            List<Map<String, Object>> cbsService = cbsServiceAssignListService.getDetailOfDistrictService(id, engineer.getId());
            if(cbsService.size() > 0){
	            request.setAttribute("cbsService", cbsService.get(0));
            }

            //附加任务信息
            List<CbsServiceTaskMapEntity> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findByProperty(CbsServiceTaskMapEntity.class, "serviceId.id", id);
            request.setAttribute("cbsServiceTaskMap", cbsServiceTaskMap);

            //服务日志
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLogOfTp(id);
            request.setAttribute("cbsServiceLogList", cbsServiceLogList);

            //文件管理
            List<Map<String, Object>> zyFileLogEntity = cbsServiceAssignListService.getFileLogByServiceId(id, "A");
            request.setAttribute("zyFileLogEntityA", zyFileLogEntity);

            //获取申请的备件
            List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailList = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.serviceId='" + id + "'");
            if (cbsEquipmentApplyDetailList.size() > 0) {
                for (CbsEquipmentApplyDetailEntity cbsEquipmentApplyDetailEntity : cbsEquipmentApplyDetailList) {
                    List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where equipmentApplyDetailId.id='" + cbsEquipmentApplyDetailEntity.getId() + "'");
                    cbsEquipmentApplyDetailEntity.setCbsDeliverEquipmentEntityList(deliverEquipmentList);
                }
            }
            request.setAttribute("cbsEquipmentApplyDetailList", cbsEquipmentApplyDetailList);
        }

        return new ModelAndView("com/zybk/cbsserviceassignlist/CbsServiceDetialsOfDistrictEngineer");
    }

    /**
     * 工程师角色服务单详情
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "detailsOfEngService")
    public ModelAndView detailsOfEngService(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            TSUser user = ResourceUtil.getSessionUserName();
            ZyEngineerEntity engineer = systemService.findUniqueByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
            //数据展示信息
            List<Map<String, Object>> cbsService = cbsServiceAssignListService.getDetailOfEng(id, engineer.getId());
            request.setAttribute("cbsService", cbsService.get(0));
            //附加任务信息
            List<CbsServiceTaskMapEntity> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findHql("from CbsServiceTaskMapEntity where serviceId.id = '" + id + "' and type is null");
            request.setAttribute("cbsServiceTaskMap", cbsServiceTaskMap);

            /*获取服务处理日志*/
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLogOfTp(id);
            request.setAttribute("cbsServiceLogList", cbsServiceLogList);

            //文件管理
            List<Map<String, Object>> zyFileLogEntity = cbsServiceAssignListService.getFileLogByServiceId(id, "A");
            request.setAttribute("zyFileLogEntityA", zyFileLogEntity);

            //获取申请的备件
            List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailList = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.serviceId='" + id + "'");
            if (cbsEquipmentApplyDetailList.size() > 0) {
                for (CbsEquipmentApplyDetailEntity cbsEquipmentApplyDetailEntity : cbsEquipmentApplyDetailList) {
                    List<Map<String, Object>> list = systemService.findForJdbc("select id,is_hb,space_number from cbs_deliver where equipment_apply_id = '" + cbsEquipmentApplyDetailEntity.getApplyId().getId() + "'");
                    if (list.size() != 0 && "1".equals(list.get(0).get("is_hb"))) {
                        List<String> id_list = systemService.findListbySql("select id from cbs_deliver where space_number like '%" + list.get(0).get("space_number") + "/%' or space_number like '%/" + list.get(0).get("space_number") + "%'");
                        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + id_list.get(0) + "'");
                        cbsEquipmentApplyDetailEntity.setCbsDeliverEquipmentEntityList(deliverEquipmentList);
                    } else {
                        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where equipmentApplyDetailId.id='" + cbsEquipmentApplyDetailEntity.getId() + "'");
                        cbsEquipmentApplyDetailEntity.setCbsDeliverEquipmentEntityList(deliverEquipmentList);
                    }
                }
            }
            request.setAttribute("cbsEquipmentApplyDetailList", cbsEquipmentApplyDetailList);
        }
        return new ModelAndView("com/zybk/cbsserviceassignlist/CbsServiceDetialsOfEngineer");
    }

    /**
     * 工程师修改备件
     *
     * @return
     */
    @RequestMapping(params = "goSparepartApply")
    public ModelAndView goSparepartApply(HttpServletRequest req) {
        String id = req.getParameter("id");
        req.setAttribute("id", id);
        String sign = req.getParameter("sign");
        req.setAttribute("sign", sign);
        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
        List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailHql = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.id='" + id + "'");
        List<CbsFaultEquipmentEntity> cbsFaultEquipmentList = systemService.findHql("from CbsFaultEquipmentEntity where applyId='" + id + "'");
        req.setAttribute("cbsFaultEquipmentList", cbsFaultEquipmentList);
        // 获取备件申请单相关联的附件
        List<ZyFileLogEntity> fileList = new ArrayList<ZyFileLogEntity>();
        String fileId = cbsEquipmentApplyEntity.getFileId();
        if (fileId != null) {
            String[] fileIdSplit = fileId.split(",");
            for (int i = 0; i < fileIdSplit.length; i++) {
                fileList.add((ZyFileLogEntity) systemService.getEntity(ZyFileLogEntity.class, fileIdSplit[i]));
            }
            req.setAttribute("fileList", fileList);
        }
        List<TSType> TSTypeList = systemService.findHql("from TSType where TSTypegroup.typegroupname='申请理由'");
        req.setAttribute("TSTypeList", TSTypeList);
        List<TSType> tSTypeHql = systemService.findHql("from TSType where TSTypegroup.typegroupname='申请优先级'");
        CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, cbsEquipmentApplyEntity.getServiceId());
        List<TSTerritory> tSTerritoryHql = systemService.findHql("from TSTerritory where territoryLevel='1'");
        req.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
        req.setAttribute("cbsEquipmentApplyDetailHql", cbsEquipmentApplyDetailHql);
        req.setAttribute("tSTypeHql", tSTypeHql);
        req.setAttribute("cbsService", cbsServiceEntity);
        req.setAttribute("tSTerritoryHql", tSTerritoryHql);
        return new ModelAndView("com/zybk/cbsserviceassignlist/applyDetail");
    }

    @ResponseBody
    @RequestMapping(params = "canEditServiceReport")
    public AjaxJson canEditServiceReport(HttpServletRequest request) {
        String id = request.getParameter("id");
        return cbsServiceServiceI.checkForEditServiceReport(id);
    }
}
